package com.fosdata.dpm.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fosdata.dpm.domain.SysXbdev;
import com.fosdata.dpm.domain.XbBasicInfo;
import com.fosdata.dpm.domain.XbDevRecoder;
import com.fosdata.dpm.entity.dto.ApiResult;
import com.fosdata.dpm.entity.dto.AppSysDevDTO;
import com.fosdata.dpm.services.*;
import com.fosdata.dpm.util.WxJsSdkSignUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * <p>
 * 小程序接口
 * </p>
 *
 * @author gyk
 * @since 2025-10-23
 */
@RestController
@RequestMapping(value = "/web-app")
public class WebAppController {


    @Autowired
    private SysXbdevServices devServices;
    @Autowired
    private XbBasicInfoServices basicInfoServices;
    @Autowired
    private XbDevRecoderServices devRecoderServices;
    @Autowired
    private SysOrgServices sysOrgServices;
    @Autowired
    private SysXbtypeServices sysXbtypeServices;


    /**
     * 扫码获取设备信息
     * */
    @GetMapping(value = "/scanTheCode")
    public ApiResult scanTheCode(String codeId){
        List<AppSysDevDTO> devDTOArrayList = new ArrayList<AppSysDevDTO>();

        if(StringUtils.isEmpty(codeId)){
            //不传 查全部箱变设备
            devDTOArrayList = basicInfoServices.getAllDev();
            return ApiResult.ok("查询成功",devDTOArrayList);
        }
        //获取箱变设备
        XbBasicInfo basicInfo = basicInfoServices.getBasicByDevCode(codeId);
        if(basicInfo==null){
            return ApiResult.error("查询箱变设备失败");
        }

        basicInfo.setOrgName(sysOrgServices.getById(basicInfo.getXbOrg()).getOrgName());
        basicInfo.setTypeName(sysXbtypeServices.getByVbCode(basicInfo.getXbType()).getXbName());
        AppSysDevDTO appSysDevDTO = new AppSysDevDTO();
        appSysDevDTO.setXbBasicInfo(basicInfo);

        //根据箱变类型获取所有箱变设备
        List<SysXbdev> sysXbdevs = devServices.getDevByDevType(basicInfo.getXbType());
        appSysDevDTO.setSysXbdev(sysXbdevs);

        //根据设备code获取相关所有信息
        if(sysXbdevs.size()>0){
            List<XbDevRecoder> recordList = devRecoderServices.getRecordByCode(sysXbdevs);
            appSysDevDTO.setRecoderList(recordList);
        }
        devDTOArrayList.add(appSysDevDTO);
        return ApiResult.ok("查询成功",devDTOArrayList);
    }


    /**
     * 小程序获取固定参数
     */
    @GetMapping(value = "/getParamForApp")
    public ApiResult getParamForApp(String appUrl){
        if (StringUtils.isEmpty(appUrl)){
            return ApiResult.error("appUrl is null");
        }
        JSONObject jsonObject = WxJsSdkSignUtil.getSignature(appUrl);
        return ApiResult.ok(jsonObject);
    }
}
